#!/usr/bin/python3

"""
MIT License

Copyright (c) 2024-2025 milkpotatoes

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import argparse
import os
import platform
import subprocess
from pathlib import Path
from datetime import datetime, timedelta

LOG_COLOR_GREEN = "\x1b[32m"
LOG_COLOR_DEFAULT = "\x1b[0m"

BUILD_ARGS = argparse.ArgumentParser()
BUILD_ARGS.add_argument(
    "-d",
    "--debug",
    action="store_true",
    help="Build debug version.",
)
BUILD_ARGS.add_argument(
    "-c",
    "--code",
    action="store_true",
    help="Build release version with debug info.",
)
BUILD_ARGS.add_argument(
    "-a",
    "--build-ark",
    action="store_true",
    help="Build napi_runner with ark. "
    "Cross platform build depdence on musl of ark build target.",
)
BUILD_ARGS.add_argument(
    "-n",
    "--no-merge-abc",
    action="store_true",
    help="Maybe useful for debug napi_runner inner ts modules, "
    "default enabled when build debug version",
)
BUILD_ARGS.add_argument(
    "-j",
    "--jobs",
    type=int,
    default=1,
    help="Jobs to build targets",
)
BUILD_ARGS.add_argument(
    "--cache",
    action="store_true",
    help="Skip regenerate cmake files if target dir is existed.",
)
BUILD_ARGS.add_argument(
    "--ark-path",
    type=str,
    required=False,
    help="Path of ark standalone.",
)
BUILD_ARGS.add_argument(
    "--verbose",
    action="store_true",
    help="Enable verbose log for cmake build.",
)
BUILD_ARGS.add_argument(
    "arch",
    type=str,
    choices=["arm", "aarch64", "arm64", "amd64", "x64"],
    help="Build type of architecture.",
)

TOOLCHAIN_OHOS = Path(__file__).with_name("toolchain").joinpath("ohos.toolchain.cmake")
TOOLCHAIN_LINUX = (
    Path(__file__).with_name("toolchain").joinpath("linux.toolchain.cmake")
)

ARCH_MAP = {
    "x86_64": "amd64",
    "amd64": "amd64",
    "aarch64": "aarch64",
    "arm64": "aarch64",
    "armv7l": "arm",
    "armv8l": "aarch64",
}

ARK_BUILD_TYPE = {
    "amd64": "x64",
    "aarch64": "arm64",
}

HOST_MAP = {
    "x86_64": "x64",
    "amd64": "x64",
    "aarch64": "arm64",
    "arm64": "arm64",
    "armv8l": "arm64",
    "armv7l": "arm",
}


def runCommand(cmd):
    if isinstance(cmd, str):
        print(f"Start to run command: {cmd}")
        cmd = cmd.split(" ")
    else:
        print(f"Start to run command: {' '.join(cmd)}")
    with subprocess.Popen(
        cmd,
        stdout=None,
        text=True,
        bufsize=1,
    ) as proc:
        proc.wait()
        return proc.returncode


def main():
    if not TOOLCHAIN_OHOS.is_file():
        raise Exception("ohos toolchain is not existed, please check repo status.")

    if not TOOLCHAIN_LINUX.is_file():
        raise Exception("Linux toolchain is not existed, please check repo status.")

    args = BUILD_ARGS.parse_args()

    BUILD_TRACE_TABLE = []

    START_BUILD_TIMESTAMP = datetime.now()
    print(
        f"{LOG_COLOR_GREEN}Start to build:{LOG_COLOR_DEFAULT} {START_BUILD_TIMESTAMP.strftime('%Y/%m/%d %H:%M:%S')}"
    )

    toolchain = TOOLCHAIN_OHOS
    crossBuild = True
    hostArch = platform.machine().lower()
    targetArch = ARK_BUILD_TYPE.get(args.arch, args.arch)
    if HOST_MAP.get(hostArch) == targetArch:
        toolchain = TOOLCHAIN_LINUX
        crossBuild = False

    generateCommand = f'cmake -DCMAKE_TOOLCHAIN_FILE="{toolchain}" '

    if crossBuild:
        generateCommand += f"-DOHOS_ARCH={args.arch} "

    generateCommand += f"-DHOST_ARCH={HOST_MAP.get(hostArch)} "

    if args.debug:
        generateCommand += "-DCMAKE_BUILD_TYPE=Debug "
    else:
        generateCommand += "-DCMAKE_BUILD_TYPE=Release "

    if args.code:
        generateCommand += "-DCODE_INFO=1 "
    else:
        generateCommand += "-DCODE_INFO=0 "

    if args.debug or args.no_merge_abc:
        generateCommand += "-DDEBUG_JS_MODULE=1 "
    else:
        generateCommand += "-DDEBUG_JS_MODULE=0 "

    arkPath = (
        Path(args.ark_path) if args.ark_path else Path().absolute().parent.absolute()
    )
    generateCommand += f'-DARK_REPO_PATH="{arkPath}" '

    outDirName = Path(
        f'build/{args.arch}-{"ohos" if crossBuild else "linux"}.{"debug" if args.debug else "release"}'
    ).absolute()

    arkOutName = f'{targetArch}.{"debug" if args.debug else "release"}'

    generateCommand += f'-B "{outDirName}"'

    if (
        args.build_ark
        or not Path(arkPath).joinpath("out").joinpath(arkOutName).is_dir()
    ):

        workDir = Path(os.curdir).absolute()
        os.chdir(arkPath)

        timestamp = datetime.now()
        BUILD_TRACE_TABLE.append(("Build arkcompiler", timestamp))
        print(
            f"{LOG_COLOR_GREEN}Start to build ark standalone project:{LOG_COLOR_DEFAULT} {timestamp.strftime('%Y/%m/%d %H:%M:%S')}"
        )
        code = runCommand(f"python3 ./ark.py {arkOutName} -j {args.jobs}")
        if code != 0:
            raise Exception(
                f"Failed to build ark standalone, return code is: {code}, please check outputs"
            )
        os.chdir(workDir)

    if not args.cache or not outDirName.is_dir():
        timestamp = datetime.now()
        BUILD_TRACE_TABLE.append(("Generate config", timestamp))
        print(
            f"{LOG_COLOR_GREEN}Start to generate config:{LOG_COLOR_DEFAULT} {timestamp.strftime('%Y/%m/%d %H:%M:%S')}"
        )

        code = runCommand(["bash", "-c", generateCommand])
        if code != 0:
            raise Exception(
                f"Failed to generate configure of napi_runner, return code is: {code}, please check outputs"
            )

    timestamp = datetime.now()
    BUILD_TRACE_TABLE.append(("Build napi_runner", timestamp))
    print(
        f"{LOG_COLOR_GREEN}Start to build napi_runner:{LOG_COLOR_DEFAULT} {timestamp.strftime('%Y/%m/%d %H:%M:%S')}"
    )

    code = runCommand(
        ["bash", "-c", f"cmake --build {outDirName} --parallel {args.jobs}" + (" --verbose" if args.verbose else "")]
    )
    if code != 0:
        raise Exception(
            f"Failed to build napi_runner, return code is: {code}, please check outputs"
        )

    FINISH_BUILD_TIMESTAMP = datetime.now()

    TOTAL_COST_TIME = (FINISH_BUILD_TIMESTAMP - START_BUILD_TIMESTAMP).total_seconds()
    print(f"{LOG_COLOR_GREEN}All build task done:{LOG_COLOR_DEFAULT} {TOTAL_COST_TIME}")

    lastTimestamp = BUILD_TRACE_TABLE[0][1]

    TABLE_TOP_BORDER = "┌─{}─┬─{}─┬─{}─┐"
    TABLE_CENTER_BORDER = "├─{}─┼─{}─┼─{}─┤"
    TABLE_BOTTOM_BORDER = "└─{}─┴─{}─┴─{}─┘"

    TABLE_HEADER = (
        "│ \x1b[1m{:<24}\x1b[0m │ \x1b[1m{:<16}\x1b[0m │ \x1b[1m{:<6}\x1b[0m │"
    )
    TABLE_CONTENT = "│ {:<24} │ {:<16} │ {:<6.2f} │"

    print(TABLE_TOP_BORDER.format("─" * 24, "─" * 16, "─" * 6))
    print(TABLE_HEADER.format("name", "total(s)", "%"))
    print(TABLE_CENTER_BORDER.format("─" * 24, "─" * 16, "─" * 6))
    for i in range(1, len(BUILD_TRACE_TABLE)):
        v = BUILD_TRACE_TABLE[i]
        cost = (v[1] - lastTimestamp).total_seconds()
        print(
            TABLE_CONTENT.format(
                BUILD_TRACE_TABLE[i - 1][0], cost, cost / TOTAL_COST_TIME * 100
            )
        )
        lastTimestamp = v[1]

    lastTrace = BUILD_TRACE_TABLE.pop()
    cost = (FINISH_BUILD_TIMESTAMP - lastTimestamp).total_seconds()
    print(TABLE_CONTENT.format(lastTrace[0], cost, cost / TOTAL_COST_TIME * 100))
    print(TABLE_BOTTOM_BORDER.format("─" * 24, "─" * 16, "─" * 6))


if __name__ == "__main__":
    main()
